package com.wzy.common.base.file;

import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/4/17 16:43
 * 4
 */
@Slf4j
public class FileUtil {
    private static ImmutableList<String> videoSuffixList = ImmutableList.of("mp4", "mov", "avi", "mkv", "m4v", "wmv",
            "asf", "asx", "rm", "rmvb", "3gp", "dat", "flv", "vob");
    /**
     * 获取视频时长 * @param file 视频文件
     * @return 时长（秒）
     */ public static double getVideoDuration(MultipartFile file){
        double duration = 0;
        File tempFile = null;
        try{
            tempFile = File.createTempFile(String.valueOf(UUID.randomUUID()), "." + FilenameUtils.getExtension(file.getOriginalFilename()));
            file.transferTo(tempFile);
            MultimediaObject multimediaObject = new MultimediaObject(tempFile);
            MultimediaInfo info = multimediaObject.getInfo();
            duration =((double) info.getDuration() / 1000.0);
        } catch (Exception e){
            log.error("获取视频时长失败", e);
        } finally {
            if (tempFile != null){
                tempFile.delete();
            }
        }
        return duration;
    }
    /**
     * 判断文件是否是视频 * @param file 文件
     * @return 是否是啊视频
     */ public static boolean isVideo(MultipartFile file){
        return videoSuffixList.contains(FilenameUtils.getExtension(file.getOriginalFilename()));
    }

    public static void main(String[] args) throws IOException {
        //MultipartFile file = new CommonsMultipartFile(new DefaultFileItem());
        //getVideoDuration(new M);
        File file = new File("F:\\PotPlayer\\Capture\\24s.mp4");
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile =  new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
        System.out.println(getVideoDuration(multipartFile));

    }

}
